using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Complaint.Models;
using Complaint.Models.Dtos.Enums;
using MvcContrib.Pagination;

namespace Complaint.Controllers
{
    public class SearchController : BaseController
    {
        //
        // GET: /Search/

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string keywords, DateTime? dateFrom, DateTime? dateTo, string categoryIdJson, int? page)
        {
            using (new UnitOfWorkScope(false))
            {
                var serializer = new JavaScriptSerializer();
                var categoryId = serializer.Deserialize<int[]>(Request.Form["categoryIDs"]);
                var model = new ComplaintModel();
                int totalCount;
                var complaints = String.IsNullOrEmpty(keywords)
                                     ? model.Retrieve(LoadComplaint.Organisation | LoadComplaint.User, page ?? 1,
                                                      PageSize, out totalCount, dateFrom, dateTo, categoryId).AsEnumerable()
                                     : model.FindByKeywords(keywords, LoadComplaint.Organisation | LoadComplaint.User,
                                                            page ?? 1, PageSize, out totalCount, dateFrom, dateTo,
                                                            categoryId).AsEnumerable();

                complaints = new CustomPagination<Models.Dtos.Complaint>(complaints, page ?? 1, PageSize, totalCount);
                ViewData["Keywords"] = keywords;

                return PartialView("Grid", complaints);
            }
        }
    }
}
